#include "loop.h"
#include "face.h"
#include <iostream>
#include "halfedge.h"
#include "vertex.h"
#include "point.h"


Loop::Loop(Face* _f)
: nextl( _f->getFloops() )
, prevl(NULL)
{
	Loop* loopOfFace = _f->getFloops();
	if( loopOfFace )
	{
    loopOfFace->prevl = this;
	}
	_f->setLoop( this );
	lface = _f;

}

Loop::~Loop()
{
  if( this->prevl )
    this->prevl->nextl = this->nextl;
  if( this->nextl )
    this->nextl->prevl = this->prevl;
  if(this == lface->getFloops())
    lface->setLoop( this->nextl );
            //if(which->l.prevl)
            //    which->l.prevl->nextl = which->l.nextl;
            //if(which->l.nextl)
            //    which->l.nextl->prevl = which->l.prevl;
            //if((Loop *) which == where->f.floops)
            //    where->f.floops = which->l.nextl;
            //break;
}

void Loop::setLedg(HalfEdge* _newhe)
{
		ledg = _newhe;
}

Loop* Loop::getPrevLoop()
{
  return prevl;
}

Face* Loop::getFace()
{
	return lface;
}
Loop* Loop::getNextl()
{
	return nextl;
}
HalfEdge* Loop::getLedg()
{
	return ledg;
}


void Loop::getCenter( double& xc, double& yc, double& zc )
{
  std::cout << "--------CENTER--------" << std::endl;
  std::cout << ".F = " << lface->getFaceno() << std::endl;
  double area= this->getArea();
  xc = 0;
  yc = 0;
  HalfEdge* h = ledg;
  do
  {
    Point* pti  = h->getVtx()->getPoint();
    Point* ptii = h->getNxt()->getVtx()->getPoint();
    double xi = pti->getX();
    double yi = pti->getY();
    double xii = ptii->getX();
    double yii = ptii->getY();
    xc += (xi+xii)*(xi*yii - xii*yi);
    yc += (yi+yii)*(xi*yii - xii*yi);
  }
  while((h = h->getNxt()) != ledg );
  xc = xc/(6.0*area);
  yc = yc/(6.0*area);
}

double Loop::getArea()
{
  std::cout << "--------AREA--------" << std::endl;
  std::cout << ".F = " << lface->getFaceno() << std::endl;
  double area=0.0;
  HalfEdge* h = ledg;
  do
  {
    std::cout << ".V = " << h->getVtx()->getVertexno() << std::endl;
    Point* pti  = h->getVtx()->getPoint();
    Point* ptii = h->getNxt()->getVtx()->getPoint();
    double xi = pti->getX();
    double yi = pti->getY();
    double xii = ptii->getX();
    double yii = ptii->getY();
    area += (xi*yii - xii*yi);
  }
  while((h = h->getNxt()) != ledg );
  area = area / 2.0;
  std::cout << "AREA = " << area << std::endl;
  return area;
}

